<template>
  <div class="order-detail">
    <el-form
      ref="orderFormRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      :disabled="type === 'view'"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="订单ID" prop="id">
            <el-input v-model="formData.id" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="订单号" prop="orderNo">
            <el-input v-model="formData.orderNo" disabled />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="客户姓名" prop="customerName">
            <el-input v-model="formData.customerName" placeholder="请输入客户姓名" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系电话" prop="customerPhone">
            <el-input v-model="formData.customerPhone" placeholder="请输入联系电话" />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="订单金额" prop="totalAmount">
            <el-input-number
              v-model="formData.totalAmount"
              :min="0"
              :precision="2"
              placeholder="请输入订单金额"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="支付方式" prop="paymentMethod">
            <el-select v-model="formData.paymentMethod" placeholder="请选择支付方式">
              <el-option label="支付宝" value="alipay" />
              <el-option label="微信支付" value="wechat" />
              <el-option label="银行卡" value="bank" />
              <el-option label="现金" value="cash" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="订单状态" prop="status">
            <el-select v-model="formData.status" placeholder="请选择订单状态">
              <el-option label="待付款" value="pending" />
              <el-option label="已付款" value="paid" />
              <el-option label="已发货" value="shipped" />
              <el-option label="已完成" value="completed" />
              <el-option label="已取消" value="cancelled" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="创建时间">
            <el-input v-model="formData.createTime" disabled />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-form-item label="收货地址" prop="address">
        <el-input
          v-model="formData.address"
          type="textarea"
          :rows="2"
          placeholder="请输入收货地址"
        />
      </el-form-item>
      
      <el-form-item label="订单备注" prop="remark">
        <el-input
          v-model="formData.remark"
          type="textarea"
          :rows="3"
          placeholder="请输入订单备注"
        />
      </el-form-item>
      
      <el-form-item label="订单商品">
        <el-table :data="formData.items" border style="width: 100%">
          <el-table-column prop="productName" label="商品名称" width="200" />
          <el-table-column prop="price" label="单价" width="100">
            <template #default="scope">
              ¥{{ scope.row.price }}
            </template>
          </el-table-column>
          <el-table-column prop="quantity" label="数量" width="100" />
          <el-table-column prop="subtotal" label="小计" width="120">
            <template #default="scope">
              ¥{{ (scope.row.price * scope.row.quantity).toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" v-if="type === 'edit'">
            <template #default="scope">
              <el-button type="danger" size="small" @click="removeItem(scope.$index)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <div class="add-item" v-if="type === 'edit'">
          <el-button type="primary" @click="addItem">添加商品</el-button>
        </div>
      </el-form-item>
      
      <el-form-item label="状态标识">
        <el-tag :type="getStatusType(formData.status)">
          {{ getStatusText(formData.status) }}
        </el-tag>
      </el-form-item>
    </el-form>
    
    <div class="form-actions" v-if="type === 'edit'">
      <el-button type="primary" @click="handleSave">保存</el-button>
      <el-button @click="handleReset">重置</el-button>
      <el-button @click="handleClose">关闭</el-button>
    </div>
    
    <div class="form-actions" v-else>
      <el-button type="primary" @click="handleEdit">编辑</el-button>
      <el-button type="success" @click="handlePay" v-if="formData.status === 'pending'">确认付款</el-button>
      <el-button type="warning" @click="handleShip" v-if="formData.status === 'paid'">确认发货</el-button>
      <el-button type="info" @click="handleComplete" v-if="formData.status === 'shipped'">确认完成</el-button>
      <el-button type="danger" @click="handleCancel" v-if="['pending', 'paid'].includes(formData.status)">取消订单</el-button>
      <el-button @click="handleClose">关闭</el-button>
    </div>
  </div>
</template>

<script>
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'OrderDetail',
  props: {
    data: {
      type: Object,
      required: true
    },
    type: {
      type: String,
      default: 'view' // view, edit
    }
  },
  data() {
    return {
      formData: {
        id: '',
        orderNo: '',
        customerName: '',
        customerPhone: '',
        totalAmount: 0,
        paymentMethod: '',
        status: 'pending',
        createTime: '',
        address: '',
        remark: '',
        items: []
      },
      formRules: {
        customerName: [
          { required: true, message: '请输入客户姓名', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        customerPhone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ],
        totalAmount: [
          { required: true, message: '请输入订单金额', trigger: 'blur' },
          { type: 'number', min: 0, message: '订单金额必须大于0', trigger: 'blur' }
        ],
        paymentMethod: [
          { required: true, message: '请选择支付方式', trigger: 'change' }
        ],
        status: [
          { required: true, message: '请选择订单状态', trigger: 'change' }
        ]
      }
    }
  },
  mounted() {
    this.initFormData()
  },
  methods: {
    initFormData() {
      this.formData = { ...this.data }
      if (!this.formData.address) {
        this.formData.address = ''
      }
      if (!this.formData.remark) {
        this.formData.remark = ''
      }
      if (!this.formData.items) {
        this.formData.items = this.generateMockItems()
      }
    },
    
    generateMockItems() {
      const products = ['iPhone 14', '华为P50', '小米13', 'MacBook Pro', '戴尔笔记本']
      const items = []
      const itemCount = Math.floor(Math.random() * 3) + 1
      
      for (let i = 0; i < itemCount; i++) {
        items.push({
          productName: products[Math.floor(Math.random() * products.length)],
          price: (Math.random() * 1000 + 100).toFixed(2),
          quantity: Math.floor(Math.random() * 3) + 1
        })
      }
      
      return items
    },
    
    getStatusType(status) {
      const statusMap = {
        'pending': 'warning',
        'paid': 'primary',
        'shipped': 'info',
        'completed': 'success',
        'cancelled': 'danger'
      }
      return statusMap[status] || 'info'
    },
    
    getStatusText(status) {
      const statusMap = {
        'pending': '待付款',
        'paid': '已付款',
        'shipped': '已发货',
        'completed': '已完成',
        'cancelled': '已取消'
      }
      return statusMap[status] || '未知状态'
    },
    
    addItem() {
      this.formData.items.push({
        productName: '',
        price: 0,
        quantity: 1
      })
    },
    
    removeItem(index) {
      this.formData.items.splice(index, 1)
    },
    
    handleSave() {
      this.$refs.orderFormRef.validate((valid) => {
        if (valid) {
          this.$emit('save', this.formData)
          ElMessage.success('保存成功')
        }
      })
    },
    
    handleReset() {
      this.initFormData()
      ElMessage.info('已重置表单')
    },
    
    handleEdit() {
      const currentRoute = this.$route
      this.$router.push({
        path: currentRoute.path,
        query: {
          ...currentRoute.query,
          action: 'edit'
        }
      })
    },
    
    handlePay() {
      ElMessageBox.confirm('确认此订单已付款？', '确认付款', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.formData.status = 'paid'
        ElMessage.success('订单状态已更新为已付款')
      })
    },
    
    handleShip() {
      ElMessageBox.confirm('确认此订单已发货？', '确认发货', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.formData.status = 'shipped'
        ElMessage.success('订单状态已更新为已发货')
      })
    },
    
    handleComplete() {
      ElMessageBox.confirm('确认此订单已完成？', '确认完成', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.formData.status = 'completed'
        ElMessage.success('订单状态已更新为已完成')
      })
    },
    
    handleCancel() {
      ElMessageBox.confirm('确认取消此订单？', '取消订单', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.formData.status = 'cancelled'
        ElMessage.success('订单已取消')
      })
    },
    
    handleClose() {
      this.$emit('close', this.$route.query.type + '-' + this.$route.query.id + '-' + this.$route.query.action)
    }
  },
  
  watch: {
    data: {
      handler(newData) {
        this.initFormData()
      },
      deep: true
    }
  }
}
</script>

<style scoped>
.order-detail {
  max-width: 900px;
}

.form-actions {
  margin-top: 30px;
  text-align: center;
  padding-top: 20px;
  border-top: 1px solid #e4e7ed;
}

.form-actions .el-button {
  margin: 0 5px;
}

.el-form-item {
  margin-bottom: 20px;
}

.add-item {
  margin-top: 10px;
  text-align: center;
}
</style>